package com.example.question.list.list1;

import java.util.Stack;

/**
 * @Date 2023-07-03
 * @Author Jonathan
 */
public class List {

    public static void main(String[] args) {
        int[] nums = new int[]{3, 1, 2, 5, 6, 4};
        ListNode listNode = createList(nums);
        printLink(listNode);
        ListNode node = copyList(listNode);
        printLink(node);
        printLink(half(node));
    }

    public static void printLink(ListNode head) {
        if (head == null) {
            return;
        }
        System.out.print("link:");
        Stack<ListNode> stack = new Stack<>();
        stack.push(head);
        while (!stack.isEmpty()) {
            ListNode node = stack.pop();
            if (node == null) return;
            System.out.print(node.val + " ");
            stack.push(node.next);
        }
    }

    public static ListNode createList(int[] nums) {
        ListNode head = new ListNode(nums[0]);
        ListNode cur = head;
        for (int i = 1; i < nums.length; i++) {
            cur.next = new ListNode(nums[i]);
            cur = cur.next;
        }
        return head;
    }

    public static ListNode copyList(ListNode head) {
        ListNode cur = head;
        while (cur != null) {
            ListNode next = cur.next;
            ListNode copyNode = new ListNode(cur.val);
            cur.next = copyNode;
            copyNode.next = next;
            cur = next;
        }
        return head;
    }

    public static ListNode half(ListNode head) {
        ListNode old = head;
        ListNode copy = head.next;
        ListNode copyHead = copy;
        while (copy != null) {
            old.next = old.next.next;
            if (copy.next != null) {
                copy.next = copy.next.next;
            }
            old = old.next;
            copy = copy.next;
        }
        return copyHead;
    }
}
